#include <cppcms/application.h>
#include <cppcms/applications_pool.h>
#include <cppcms/service.h>
#include <cppcms/http_response.h>
#include <cppcms/url_dispatcher.h>
#include <cppcms/url_mapper.h>
#include <cppcms/http_request.h>
#include <iostream>
#include <nlohmann/json.hpp>

#include <stdlib.h>
#include <regex>
#include <string>
#include <cstring>
#include <unistd.h>
#include <typeinfo>
#include <sstream>
// #include "time.cpp"
#include "sqlite3.cpp"
// #include "filestream.cpp"


using namespace std;
using json=nlohmann::json;

class web : public cppcms::application {
public:
    web(cppcms::service &srv) :cppcms::application(srv)
    {
        // dispatcher().assign("/number/(\\d+)",&web::number,this,1);
        //    mapper().assign("number","/number/{1}");


        dispatcher().assign("/request",&web::request,this);
        mapper().assign("request","/request{1}");



        dispatcher().assign("/index",&web::index,this);
        mapper().assign("/index");

        mapper().root("/web");
    }
    
    virtual void request();
    virtual void index();
};

void web::index()
{
    // const char* path="time.json";
    // std::string s=file_get_contents(path);
    string sql="select * from stime where id=1;";
    string r=sqlite3_select(sql);
    json rj=json::parse(r);

    string res=rj[0][1];
      
    response().set_header("Access-Control-Allow-Origin","*");
    response().set_header("Access-Control-Allow-Methods","*");
    response().set_header("Access-Control-Allow-Headers","*");
    response().set_header("Access-Control-Allow-Credentials", "true");
    response().content_type("application/json; charset=utf-8");
    response().out() << res;
}

void web::request()
{
    // const char* path="milliseconds.json";
    // std::string s=file_get_contents(path);

    string sql="select * from stime where id=2;";
    string r=sqlite3_select(sql);
    json rj=json::parse(r);

    string res=rj[0][1];
    
    response().set_header("Access-Control-Allow-Origin","*");
    response().set_header("Access-Control-Allow-Methods","*");
    response().set_header("Access-Control-Allow-Headers","*");
    response().set_header("Access-Control-Allow-Credentials", "true");
    response().content_type("application/json; charset=utf-8");
    
    response().out() << res;
}



int main(int argc,char ** argv)
{
    
    try {
        cppcms::service srv(argc,argv);

        srv.applications_pool().mount(
          cppcms::applications_factory<web>()
        );
        srv.run();
    }
    catch(std::exception const &e) {
        std::cerr << e.what() << std::endl;
    }
}
